package com.eam.handler;

import com.eam.data.EamSpareparts;
import com.eam.data.EamSparepartsInventory;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 设备备品配件盘点
 * 
 */
public class SparepartInventorybuttonHandler extends BaseActionHandler {
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//处理时间格式

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject jsonRep = new JSONObject();
		String meg = "";
		try {
			JSONObject request = new JSONObject(content);

			jsonRep.put("flag", true);

			JSONArray jsonIds = request.getJSONArray("dateParam");
			
			JSONObject reqData = null;
			
			
			for (int i = 0;i < jsonIds.length();i ++) {
				
				
				reqData = jsonIds.getJSONObject(i);
				
				String resultId = reqData.getString("PlanIds");  //获取行ID
				String code = reqData.getString("ASN_CODE");  //获取物料编码
				//String Master = reqData.getString("M_Locator");		//获取库位
				String company = reqData.getString("company");		//获取单位
				String quantitys = reqData.getString("quantity");		//获取盘点数量
				//String rknumbers = reqData.getString("M_VENDOR");		//获取库存数量
				//String GUCODE = reqData.getString("emesProcessopr");		//获取工序
				String remarks = reqData.getString("remarks");		//获取备注				
				Date time  =sdf.parse(sdf.format(new Date())); //获取当前系统时间
				
				String status = "";  //代表盘点状态是盘盈还是盘亏
				
				String pandianstatus = "Audit";
				
				//查询当家登录账户的ID
				String userIdtime = SessionInfo.getUserId(); //登录人的ad_user_id
				
				String eql = "select * from ad_user where ad_user_id = ?";
				
				User userIds = (User)OBDal.getInstance().getSession().createSQLQuery(eql).addEntity(User.ENTITY_NAME).setString(0, userIdtime).uniqueResult();
				
				//查询物料清单ID
				String  sql = "select * from Eam_Spareparts where Eam_Spareparts_id  = ? ";
				
				EamSpareparts wlIds = (EamSpareparts)OBDal.getInstance().getSession().createSQLQuery(sql).addEntity(EamSpareparts.ENTITY_NAME).setString(0, resultId).uniqueResult();
				
				/*//查询库位ID
				String aql = "select * from M_Locator where value = ? ";
				
				Locator kwids = (Locator)OBDal.getInstance().getSession().createSQLQuery(aql).addEntity(Locator.ENTITY_NAME).setString(0, Master).uniqueResult();*/
				
			/*	//查询设备ID
				String wql = "select * from Eam_Facilities where code = ? ";
				
				EamFacilities sbids = (EamFacilities)OBDal.getInstance().getSession().createSQLQuery(wql).addEntity(EamFacilities.ENTITY_NAME).setString(0, SBCODE).uniqueResult();
				*/
				
				//查询当前库位的库存数量
				String aql = "select ((select sum(jl.numbers)   "
						+ "from Eam_Spareparts_Collar jl  "
						+ " left join Eam_Spareparts  wl on jl.Eam_Spareparts_id = wl.Eam_Spareparts_id   "
						+ " left join m_locator cw on cw.m_locator_id = jl.m_locator_id   "
						+ "  where jl.type = 'added' and wl.code = '"+code+"') - "
						+ " (select NVL(sum(jl.numbers), 0)  from Eam_Spareparts_Collar jl "
						+ " left join Eam_Spareparts  wl on jl.Eam_Spareparts_id = wl.Eam_Spareparts_id  "
						+ " left join m_locator cw on cw.m_locator_id = jl.m_locator_id "
						+ " where jl.type = 'Out' and wl.code = '"+code+"' and jl.status != 'Notthrough')) as qty  from dual ";
				
				Long sumqty = (Long)OBDal.getInstance().getSession().createSQLQuery(aql).uniqueResult();
				
				int sumqtys = Integer.parseInt(String.valueOf(sumqty)); 
				
				String companys  = "";
		  		
		  		if( company.equals("对")){
					companys= "10";
				}else if( company.equals("个")){
					companys= "20";
				}else if( company.equals("根")){
					companys= "30";
				}else if( company.equals("盒")){
					companys= "40";
				}else if( company.equals("卷")){
					companys= "50";
				}else if( company.equals("块")){
					companys= "60";
				}else if( company.equals("片")){
					companys= "70";
				}else if( company.equals("套")){
					companys= "80";
				}
				
				//存物料清单表
				//EamSpareparts  materiel =  OBDal.getInstance().get(EamSpareparts.class, resultId);  //获取选中的物料清单
				
				/*//如果盘点数量不填则默认其数量是库存数量，是正确的
				if(quantitys.equals("")){
					quantitys = rknumbers;
				}*/
				
				int quantity = Integer.parseInt(quantitys);      //转化后的盘点数量
		  	
		  		
		  		if(quantity > sumqtys){
		  		    status = "Profit";
		  			
		  		}else if(quantity < sumqtys){
		  		    status = "loss";
		  		}else{
		  			status = "normal";
		  		}
		  		//BigDecimal kunumbers = new BigDecimal(rknumber);   //盘点前库存数量
	  			BigDecimal sumnumber = new BigDecimal(quantity);  // 盘点数量
	  		    
	  			//materiel.setNumbers(sumnumber);
	  		    //materiel.setProfitLossStatus(status);
	  		   // materiel.setProfitLossNumbers(sumnumber);
	  		    //materiel.setStatus(pandianstatus);
		  		//OBDal.getInstance().save(materiel);
		  		
		  		
		  		//存盘点记录表
		  		EamSparepartsInventory Inventory = new EamSparepartsInventory();
		  		
		  		Inventory.setEamSpareparts(wlIds);
		  		//Inventory.setLocator(kwids);
		  		Inventory.setCompany(companys);
		  		Inventory.setNumbers(sumnumber);
		  		//Inventory.setInventoryNumbers(kunumbers);
		  		
		  		//Inventory.setEamFacilities(sbids);
		  		Inventory.setInventoryTime(time);
		  		Inventory.setStatus(status);
		  		Inventory.setUser(userIds);
		  		Inventory.setRemarks(remarks);
		  		Inventory.setSparefield(pandianstatus);
		  		OBDal.getInstance().save(Inventory);
			}

			if(meg.equalsIgnoreCase("")){
				jsonRep.put("flag", true);
				jsonRep.put("message", "处理成功");
				OBDal.getInstance().commitAndClose();
			}else{
				jsonRep.put("flag", false);
				jsonRep.put("message",meg);
				OBDal.getInstance().rollbackAndClose();
			}
			
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		} finally {
			OBContext.restorePreviousMode();
		}
        
		return jsonRep;
	}
}